import 'dart:io';

import 'package:agent_process_app/utils/myUtils.dart' as myUtils;
import 'package:agent_process_app/widgets/drawerScreen/switch_nightMode.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MyDrawer extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return DrawerScreen();
  }
}

class DrawerScreen extends State<MyDrawer> {
  String userName = "";
  String nickName = "";
  Widget headImg;

  Widget versionStatus = Icon(Icons.keyboard_arrow_right);

  getUserInfo() async {
    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      setState(() {
        userName = sharedPreferences.getString("userName");
      });
    });

    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      setState(() {
        nickName = sharedPreferences.getString("nickName");
      });
    });

    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      String imgUrl = sharedPreferences.getString("imgUrl");
      try {
        //有头像
        if (imgUrl != null && imgUrl.length > 3) {
          //查看到第二个斜杠的下标,并从该下标+1的位置截取到最后
          int urlIndex = imgUrl.indexOf("/", 2) + 1;
          String prefixImgUrl = imgUrl.substring(0, urlIndex);
          String suffixImgUrl = imgUrl.substring(urlIndex, imgUrl.length);
          print(imgUrl);
          setState(() {
            headImg = CircleAvatar(
              //用了图片缓存技术
              backgroundImage: CachedNetworkImageProvider(
                  myUtils.MyDio.baseUrl + prefixImgUrl + suffixImgUrl),

              //未使用图片缓存技术
//              backgroundImage: NetworkImage(
//                  myUtils.MyDio.baseUrl + prefixImgUrl + suffixImgUrl),
              backgroundColor: Colors.white,
            );
          });
        } else {
          setState(() {
            headImg = CircleAvatar(
              backgroundColor: Colors.white,
              child: Text(
                nickName.substring(0, 1),
                style: TextStyle(fontSize: 40.0),
              ),
            );
          });
        }
      } catch (e) {
        setState(() {
          headImg = CircleAvatar(
            backgroundColor: Colors.white,
            child: Text(
              nickName.substring(0, 1),
              style: TextStyle(fontSize: 40.0),
            ),
          );
        });
      }
    });
  }

  //打开drawer时触发
  checkVersion() async {
    try {
      await myUtils.LocalStorage.getLocalStorageInstance()
          .then((SharedPreferences sharedPreferences) {
        String newVersionUrl = "";
        try {
          newVersionUrl = sharedPreferences.getString("newVersionUrl");
        } catch (e) {
          print(e);
        }
        print(newVersionUrl);
        if (newVersionUrl.isEmpty ||
            newVersionUrl == "" ||
            newVersionUrl.length < 3) {
          setState(() {
            versionStatus = Icon(Icons.keyboard_arrow_right);
          });
          return;
        } else {
          //检测到新版本
          setState(() {
            versionStatus = Icon(
              Icons.fiber_new,
              color: Theme.of(context).primaryColor,
              size: 30.0,
            );
          });
          checkVersionByClick();
        }
      });
    } catch (e) {
      print(e);
      setState(() {
        versionStatus = Icon(Icons.keyboard_arrow_right);
      });
    }
  }

  //手动点击"检查更新"触发
  checkVersionByClick() async {
    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      token = sharedPreferences.getString("token");
    });

    //获取新版本
    Dio dio = myUtils.MyDio.getDio(token);
    Response response;

    //发送打开App请求,在后台记录
    try {
      response = await dio.get(
        "/checkVersion",
      );
      print(response.statusCode);
      print(response.data);
      int statusCode = response.data["Code"];
      String resVersion = await response.data["Data"]["Version"];
      String resUrl = await response.data["Data"]["Url"];
      if (statusCode == 200) {
        //如果有新版本
        if (resVersion.isNotEmpty && myUtils.AppInfo.version != resVersion) {
          print(resVersion);
          print("有新版本啦");
          //持久化
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString("newVersionUrl", resUrl);
          });
          //添加Icon图标
          setState(() {
            versionStatus = Icon(
              Icons.fiber_new,
              color: Theme.of(context).errorColor,
              size: 30.0,
            );
          });
          //选择是否现在更新
          print("选择是否现在更新");
          await showDialog(
              context: context,
              builder: (_) => new AlertDialog(
                      title: new Text("更新提示"),
                      content: new Text("检测到新版本 v$resVersion,请及时更新!"),
                      actions: <Widget>[
                        new FlatButton(
                          child: new Text("取消"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        ),
                        new FlatButton(
                          child: new Text("更新"),
                          onPressed: () {
                            Navigator.of(context).pop();
                            myUtils.MyUtils.launchURL(resUrl);
                          },
                        )
                      ]));
        } else {
          print("无新版本");
          await showDialog(
              context: context,
              builder: (_) => new AlertDialog(
                      title: new Text("当前版本为最新版本!"),
                      actions: <Widget>[
                        new FlatButton(
                          child: new Text("确定"),
                          onPressed: () {
                            Navigator.of(context).pop();
                          },
                        )
                      ]));
          await myUtils.LocalStorage.getLocalStorageInstance()
              .then((SharedPreferences sharedPreferences) {
            sharedPreferences.setString("newVersionUrl", "");
          });
          setState(() {
            versionStatus = Icon(Icons.keyboard_arrow_right);
          });
        }
      }
    } catch (e) {
      print(e);
      //在这里判断网络是否正常  2019年2月14日 17:28:25
    }
  }

  //上传头像
  uploadUserImage(ImageSource source) async {
    File _imageFile;
    try {
      _imageFile = await ImagePicker.pickImage(source: source);
      if (_imageFile == null) {
        print("未选择图片");
        return;
      }
    } catch (e) {
      print(e);
      print("未选择图片");
      return;
    }

    setState(() {
      headImg = CircleAvatar(
        backgroundColor: Colors.white,
        child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation(
          Theme.of(context).primaryColor,
        )),
      );
    });

    FormData formData = new FormData.from({
      "userImg": new UploadFileInfo(new File(_imageFile.path), "userImg.jpg"),
    });

    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
        .then((SharedPreferences sharedPreferences) {
      token = sharedPreferences.getString("token");
    });

    Dio dio = myUtils.MyDio.getDio(token);
    Response response = await dio.post("/uploadUserImg", data: formData);
    print(response.statusCode);
    print(response.data);
    int resCode = response.data["Code"];
    if (resCode == 200) {
      //更换头像的url
      String imgUrl = response.data["Data"];
      //查看到第二个斜杠的下标,并从该下标+1的位置截取到最后
      int urlIndex = imgUrl.indexOf("/", 2) + 1;
      String prefixImgUrl = imgUrl.substring(0, urlIndex);
      String suffixImgUrl = imgUrl.substring(urlIndex, imgUrl.length);

      setState(() {
        headImg = CircleAvatar(
          backgroundImage: CachedNetworkImageProvider(
              myUtils.MyDio.baseUrl + prefixImgUrl + suffixImgUrl),
          backgroundColor: Colors.white,
        );
      });

      await showDialog(
          context: context,
          builder: (_) =>
              new AlertDialog(title: new Text("头像上传成功!"), actions: <Widget>[
                new FlatButton(
                  child: new Text("确定"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                )
              ]));
      //将imgUrl持久化
      await myUtils.LocalStorage.getLocalStorageInstance()
          .then((SharedPreferences sharedPreferences) {
        sharedPreferences.setString("imgUrl", imgUrl);
      });
    } else if (resCode == 403) {
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("安全提醒"),
                  content: new Text("由于登录已过期,本次头像上传失败,请重新登录后重试!"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();

                        SharedPreferences.getInstance().then((s) {
                          myUtils.MyUtils.clearUserInfo();
                          Navigator.of(context).pushNamedAndRemoveUntil(
                              "/loginScreen", (route) => route == null);
                        });
                      },
                    )
                  ]));
    }

    //将url持久化
//        await myUtils.LocalStorage.getLocalStorageInstance()
//                .then((SharedPreferences sharedPreferences) {
//            sharedPreferences.setString("imgUrl", "");
//        });

    //刷新当前页面的用户信息
//        getUserInfo();
  }

  chooseCameraGallery() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机"),
                onTap: () async {
                  uploadUserImage(ImageSource.camera);
                  Navigator.pop(context);
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("图库"),
                onTap: () async {
                  uploadUserImage(ImageSource.gallery);
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }

  @override
  void initState() {
    super.initState();
    try {
      //获取用户信息
      getUserInfo();
      //检查更新
      checkVersion();
    } catch (e) {}
  }

  @override
  Widget build(BuildContext context) {
    logout() async {
      bool logoutTF = false;
      await showDialog(
          context: context,
          builder: (_) => new AlertDialog(
                  title: new Text("切换账号"),
                  content: new Text("确定退出到登录界面吗？"),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text("点错了"),
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                    ),
                    new FlatButton(
                      child: new Text("确定"),
                      onPressed: () {
                        Navigator.of(context).pop();
                        logoutTF = true;
                      },
                    )
                  ]));
      if (logoutTF) {
        myUtils.MyUtils.clearUserInfo();
        Navigator.of(context)
            .pushNamedAndRemoveUntil("/loginScreen", (route) => route == null);
      }
    }

    // TODO: implement build
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          UserAccountsDrawerHeader(
            accountName: Text(
              nickName != null ? nickName : "",
              style: TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            accountEmail: Text(userName != null ? userName : ""),
            currentAccountPicture: InkWell(
              child: headImg,
              onTap: chooseCameraGallery,
            ),
            //背景图
            decoration: BoxDecoration(
                color: Theme.of(context).primaryColor,
                image: DecorationImage(
                    image: AssetImage('images/drawer_bg.jpg'),
                    fit: BoxFit.fill,
                    colorFilter: ColorFilter.mode(
                        Theme.of(context).primaryColor.withOpacity(0.6),
                        BlendMode.hardLight))),
          ),
          InkWell(
            child: ListTile(
              leading: Icon(
                Icons.update,
              ),
              title: Text(
                "检查更新",
              ),
//                        subtitle: Text("发现新版本!",style: TextStyle(Theme.of(context).errorColor),),
              trailing: versionStatus,
            ),
            onTap: () {
              checkVersionByClick();
            },
          ),
          ListTile(
            leading: Icon(
              Icons.lock_open,
            ),
            title: Text("修改密码"),
            onTap: () {
              Navigator.pushNamed(context, "/changePwd_screen");
            },
            trailing: Icon(Icons.keyboard_arrow_right),
          ),
          ListTile(
            leading: Icon(
              Icons.exit_to_app,
            ),
            title: Text("切换账号"),
            onTap: logout,
            trailing: Icon(Icons.keyboard_arrow_right),
          ),
          ListTile(
            leading: Icon(
              Icons.info_outline,
            ),
            title: Text("关于我们"),
            onTap: () {
              Navigator.pushNamed(context, "/aboutUs");
            },
            trailing: Icon(Icons.keyboard_arrow_right),
          ),
          ListTile(
            leading: Icon(
              Icons.lightbulb_outline,
            ),
            title: Text("夜间模式"),
            trailing: NightMode(),
          ),
//                    Container(
//                        padding: EdgeInsets.only(top: 240.0),
//                        child: Text(
//                            "版本v${myUtils.AppInfo.version}",
//                            textAlign: TextAlign.center,),
//                    )
        ],
      ),
    );
  }
}
